import axios from 'axios'
import { Toast, Notify } from 'vant'
import qs from 'qs'
// import store from '@/store'
// import { getToken, removeToken } from '@/utils/auth'
// import router from '@/router'

let toast
function startLoading () {
  toast = Toast.loading({
    duration: 0,
    forbidClick: true,
    message: "请求中..."
  });
}
function endLoading () {
  toast.clear()
}

let needLoadingRequestCount = 0
export function showFullScreenLoading () {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}

export function tryHideFullScreenLoading () {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: '/api', // url = base url + request url
  // baseURL: import.meta.env.VITE_BASE_API, // url = base url + request url
  // baseURL: 'https://api.glink-edu.com/index.php', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000, // request timeout
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // if (store.getters.token) {
    // let each request carry token
    // ['X-Token'] is a custom headers key
    // please modify it according to the actual situation
    // config.headers['Cookie'] = 
    // if (!config.params.noLoading) {
    showFullScreenLoading()
    // }
    // }
    config.data = qs.stringify(config.data)
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    tryHideFullScreenLoading()
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    // if (res.code !== 0 && res.msg !== '现无数据') {
    //   // Toast.fail({
    //   //   message: res.msg || 'Error',
    //   //   duration
    //   // })
    //   Notify(res.msg || 'Error')
    //   tryHideFullScreenLoading()
    //   return res
    //   // tryHideFullScreenLoading()
    //   // return Promise.reject(new Error(res.msg || 'Error'))
    // } else {
    //   tryHideFullScreenLoading()
    //   return res
    // }
    tryHideFullScreenLoading()
    return res
  },
  error => {
    // if (!error.response) {
    //   tryHideFullScreenLoading()
    //   Notify('系统繁忙,请刷新页面')
    // }
    // if (error.response.status === 403) {
    //   removeToken()
    //   router.push({ path: '/login' })
    //   Notify('系统繁忙,请重新登录')
    // }
    tryHideFullScreenLoading()
    return Promise.reject(error)
  }
)

export default service
